package com.test.rabbitmq.nack;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

public class MyConsumer extends DefaultConsumer {

    private Channel channel;

    public MyConsumer(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

        System.out.println("==body: " + new String(body));
        super.handleDelivery(consumerTag, envelope, properties, body);
        System.out.println("==properties: " + properties.getHeaders().get("pc"));
        Integer num = (Integer) properties.getHeaders().get("num");

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        /**
         * 第1条数据的num是0，会进到nack
         * 然后这条消息会从新回到队列
         * 回到队列的尾部，被重新消费
         */
        if (num == 0) {
            // TODO 最后一个参数 requeue 设置为true 会把消费失败的消息从新添加到队列的尾端，设置为false不会重新回到队列
            channel.basicNack(envelope.getDeliveryTag(), false, true);
            System.out.println("==============第：" + num + "条消息------没有被消费");
        } else {
            System.out.println("==============第：" + num + "条消息-------被消费");
            channel.basicAck(envelope.getDeliveryTag(), false);
        }
    }
}
